package cs.study.base.conn009;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 阻塞的队列 当队列大小达到某个值时不能再在put，当队列空时不能take要阻塞线程
 * @Author: 陈胜
 * @Date: 2018/1/26 15:01
 */
public class MyQueue {

    //1.需要一个承装元素的集合
    private final LinkedList<Object> list = new LinkedList<Object>();

    //2.需要一个计数器
    private AtomicInteger count = new AtomicInteger(0);

    //3.需要指定上限和下限
    private int minSize = 0;
    private int maxSize;

    //4.构造方法
    public MyQueue(int size) {
        this.maxSize = size;
    }

    //5.初始化一个对象用于加锁
    private final Object lock = new Object();

    /**
     * 放入一个元素
     * @param obj
     */
    public void put(Object obj) {
        synchronized (lock) {
            while (count.get() == this.maxSize) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //1.加入元素
            list.add(obj);
            //2.计数器累加
            count.incrementAndGet();
            //3.通知另一个线程（唤醒）
            lock.notify();
            System.out.println("新加入的元素为：" + obj);
        }
    }

    /**
     * 取出一个元素
     * @return
     */
    public Object take() {
        Object ret = null;
        synchronized (lock) {
            while (count.get() == this.minSize) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //1.移除元素操作
            ret = list.removeFirst();
            //2.计数器递减
            count.decrementAndGet();
            //3.唤醒另一个线程
            lock.notify();
        }
        return ret;
    }

    /**
     * 返回队列容量
     * @return
     */
    public int getSize() {
        return this.count.get();
    }

    public static void main(String[] args) {
        final MyQueue mq = new MyQueue(5);
        mq.put("a");
        mq.put("b");
        mq.put("c");
        mq.put("d");
        mq.put("e");

        System.out.println("当前容器的长度：" + mq.getSize());

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                mq.put("f");
                mq.put("g");
            }
        }, "t1");
        t1.start();

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                Object o1 = mq.take();
                System.out.println("移除的元素为：" + o1);
                Object o2 = mq.take();
                System.out.println("移除的元素为：" + o2);
            }
        }, "t2");

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t2.start();
    }
}
